<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 * 
 * 创建时间：2021-10-15 08:53
 *
 * 项目：rm  -  $  - zipUploadServerHelper.php
 *
 * 作者：liwei 
 */

namespace modules\levmodules\helpers;

use Lev;
use lev\base\Adminv;
use lev\helpers\curlHelper;
use lev\helpers\ModulesHelper;
use lev\helpers\UrlHelper;
use modules\levs\modules\ftp\controllers\FormUploadZipsController;
use modules\levstore\controllers\ApiController;

!defined('INLEV') && exit('Access Denied LEV');


class zipUploadServerHelper
{

    public static function getUploadPwd($id) {
        if (is_file($file = __DIR__ . '/.ftpServerAdminPwd.php')) {
            $config = include $file;
            return Lev::arrv($id, $config, '');
        }
        return false;
    }
    public static function getStoreAccesstoken() {
        return static::getUploadPwd('store-accesstoken-1');
    }

    public static function upload($id, $mudInfo)
    {
        $servers = levmodulesSetHelper::serversOpen();
        if (empty($servers[$id])) {
            return Lev::responseMsg(-12, '查无此服务器id：'.$id);
        }

        $uploadPwd = $servers[$id]['uploadPwd'] ?: static::getUploadPwd($id);
        return static::doCurlUpload($servers[$id]['serverDomain'], $uploadPwd, $mudInfo);
    }

    /**
     * @param $iden
     * @return array
     *
     * @see ApiController::actionIndex()
     */
    public static function uploadStore($iden) {
        $mudInfo = ModulesHelper::getModuleInfo($iden);
        //$domain = UrlHelper::store(false);
        $domain = levmodulesSetHelper::storeApiDomain();
        $url = $domain . '/levs.php?id=levstore&r=api&devuid='.levmodulesSetHelper::devloperUid().'&token='.levmodulesSetHelper::accesstoken();
        return static::doCurlUpload($domain, 'levme.com', $mudInfo, $url, true);
    }

    /**
     * @param $domain
     * @param $password
     * @param $mudInfo
     * @return array
     *
     * @see FormUploadZipsController::actionApi() 服务器接收方法
     */
    public static function doCurlUpload($domain, $password, $mudInfo, $url = '', $README = false) {
        $pm['url'] = ($url ?: trim(trim($domain), '/') . '/levs.php?id=levs:ftp&r=form-upload-zips/api');
        $pm['url'].='&showErr=1&adminSign='.Adminv::getAdminSign($password, Lev::$app['timestamp']);

        $zipInfos = static::zipInfos($mudInfo);
        if (isset($zipInfos['error'])) {
            return $zipInfos;
        }

        $pm['post'] = [
            'timestamp'=> Lev::$app['timestamp'],
            'mudInfo'  => json_encode($mudInfo),
            'iden'     => $mudInfo['identifier'],
            'version'  => $mudInfo['version'],
            'mudFiles' => json_encode($zipInfos['mudFiles']),
            'changeFiles' => json_encode($zipInfos['changeFiles']),

            'siteurl'  => Lev::base64_encode_url(Lev::$aliases['@siteurl']),
        ];
        $pm['upload']['zip'] = $zipInfos['filename'];
        $README && $pm['upload']['readmezip'] = $zipInfos['readme'];
        //$pm['_error'] = 1;
        $pm['timelimit'] = 300;//五分钟
        $pm['time'] = 300;
        $res = curlHelper::doCurl($pm);
        $arr = json_decode($res, true);
        if (isset($arr['succeed'])) {
            zipHelper::clearCache($mudInfo['identifier']);
            return Lev::responseMsg(1, '<b class="color-green">上传成功:' . $domain .'</b>', [$arr,$pm]);
        }else {
            $errMsg = empty($arr['message']) ? Lev::stripTags($res) : $arr['message'];
            return Lev::responseMsg(-1, '上传失败:' . $errMsg . ' -> ' . $domain, [$arr,$res, $pm]);
        }
    }

    public static function zipInfos($mudInfo) {
        $verDir = zipHelper::getMudVersionDir($mudInfo['identifier'], $mudInfo['version']);
        if (!is_file($filename = $verDir . ($mudInfo['classdir'] ?: $mudInfo['identifier']) . '.zip')) {
            return Lev::responseMsg(-12, '没有压缩包，无法上传');
        }
        return [
            'filename' => $filename,
            'readme'   => zipHelper::getMudREADME_zip($mudInfo['identifier'], $mudInfo['classdir']),
            'mudFiles' => is_file($file = $verDir . 'mudFiles.php') ? include $file : [],
            'changeFiles' => is_file($file = $verDir . 'changeFiles.php') ? include $file : [],
        ];
    }
}